package com.tevintao.marketingsystem.services;

import android.content.Context;
import android.text.TextUtils;

import com.tevintao.marketingsystem.log.LogManager;
import com.tevintao.marketingsystem.shell.Shell;
import com.tevintao.marketingsystem.tool.PackageTool;
import com.tevintao.marketingsystem.tool.SystemPathTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


public class AccountManager {

    public static final String TAG = AccountManager.class.getSimpleName();


    public static final String SD_MS_ROOT = "/mnt/sdcard/MS";

    public static final String APK_PATH = SD_MS_ROOT + "/weixin.apk";

    public static final String GIF_SHOW_PACKAGE_NAME = "com.smile.gifmaker";
    public static final String WX_PACKAGE_NAME = "com.tencent.mm";

    public static final String MM_DATA_ROOT = "/data/data/" + WX_PACKAGE_NAME;

    public static final String DATA_DATA = "/data/data/";


    public static final int TYPE_DEVICE_LENOVO = 1; //联想设备，模拟所有信息
    public static final int TYPE_DEVICE_SANXIN = 2;//三星，比联想手机少一个属性
    public static final int TYPE_DEVICE_BUSSINESS = 3;
    public static final int TYPE_NO_DEVICE_INFO = 4;//不模拟设备信息
    public static int CURREN_DEVICE_TYPE = TYPE_NO_DEVICE_INFO;
    /**
     * 存放帐号数据的目录
     */
    public static final String ACCOUNT_DATA_CACHE_PATH = DATA_DATA + "account_cache/";
    public static final String ACCOUNT_NAME_FILE_NAME = "account.txt";
    public static final String ACCOUNT_DEVICE_INFO_FILE_NAME = "device.txt";

    public static final String ACCOUNT_NET_TYPE_FILE_PATH = ACCOUNT_DATA_CACHE_PATH + "net.txt";

    public static final String CLEAN_DATA_FOLDER_PATH = ACCOUNT_DATA_CACHE_PATH + "clean";

    public static final String TEST_DATA_FOLDER_PATH = ACCOUNT_DATA_CACHE_PATH + "test";

    public static final String LOCAL_DEVICE_INFO = ACCOUNT_DATA_CACHE_PATH + "localdev.txt";

    public static final String LOCATION_FILE_NAME = "location.txt";

    public static final String DEVICE_FILE = MM_DATA_ROOT + "/" + ACCOUNT_DEVICE_INFO_FILE_NAME;
    public static final String LOCATION_FILE = MM_DATA_ROOT + "/" + LOCATION_FILE_NAME;

    public static final String KEY_TEST_DEVICE_INFO = "test";


    public static final String TENCENT_NAME = "Tencent";
    public static final String MM_SD_PATH = new File("/mnt/sdcard/", TENCENT_NAME).getAbsolutePath();

    public static final String MM_SD_CACHE_PATH = new File("/mnt/sdcard/", "MS").getAbsolutePath();

    public static final String PICTURE_PATH = new File(MM_SD_CACHE_PATH, "pic").getAbsolutePath();
    public static final String PICTURE_RANDOM_PATH = new File(MM_SD_CACHE_PATH, "randomPic").getAbsolutePath();

    public static final String SEND_MESSAGE_FILE = SD_MS_ROOT + "/sendMessageHiostory";
    public static final String SYSTEM_ERROR_MESSAGE_FILE = SD_MS_ROOT + "/systemerror.txt";

    public static final String DEVICE_FILE_NAME = "device_name";
    private static AccountManager ourInstance;

    public static final String SUCCESS_TAG = "SUCCESS";

    public static AccountManager getInstance(Context mContext) {
        if (ourInstance == null) {
            ourInstance = new AccountManager(mContext);
        }
        return ourInstance;
    }

    private Context mContext;

    private AccountManager(Context context) {
        this.mContext = context;
    }


    public String checkContextTag() {
        if (!PackageTool.isAppInstalled(mContext, WX_PACKAGE_NAME)) {
            messageChange("(error)应用未安装");
            return "应用未安装";
        }
        messageChange("应用已经安装");

        if (!SystemPathTool.exitPath(ACCOUNT_DATA_CACHE_PATH)) {
            messageChange("(error)缓存根目录不存在" + ACCOUNT_DATA_CACHE_PATH);
            return "缓存根目录不存在";
        }
        messageChange("缓存根目录存在" + ACCOUNT_DATA_CACHE_PATH);

        if (!SystemPathTool.exitFile(LOCAL_DEVICE_INFO)) {
            messageChange("不存在默认的网络设备信息");
            return "不存在默认的网络设备信息";
        }
        if (SystemPathTool.exitPath(CLEAN_DATA_FOLDER_PATH)) {
            messageChange("干净缓存根目录存在" + CLEAN_DATA_FOLDER_PATH);
            return SUCCESS_TAG;
        } else {
            messageChange("(error)干净缓存根目录不存在" + CLEAN_DATA_FOLDER_PATH);
            return "干净缓存根目录不存在";
        }
    }

    private boolean checkContext() {
        if (!PackageTool.isAppInstalled(mContext, WX_PACKAGE_NAME)) {
            messageChange("(error)应用未安装");
            return false;
        }
        messageChange("应用已经安装");

        if (!SystemPathTool.exitPath(ACCOUNT_DATA_CACHE_PATH)) {
            messageChange("(error)缓存根目录不存在" + ACCOUNT_DATA_CACHE_PATH);
            return false;
        }
        messageChange("缓存根目录存在" + ACCOUNT_DATA_CACHE_PATH);

        if (SystemPathTool.exitPath(CLEAN_DATA_FOLDER_PATH)) {
            messageChange("干净缓存根目录存在" + CLEAN_DATA_FOLDER_PATH);
            return true;
        } else {
            messageChange("(error)干净缓存根目录不存在" + CLEAN_DATA_FOLDER_PATH);
            return false;
        }
    }

    public boolean createContext() {
        if (PackageTool.isAppInstalled(mContext, WX_PACKAGE_NAME)) {
            messageChange("微信 已经安装");
            boolean success = PackageTool.uninstall(WX_PACKAGE_NAME);
            if (success) {
                messageChange("微信卸载成功");
            } else {
                messageChange("(error) 微信 卸载失败");
                return false;
            }
        }
        if (SystemPathTool.exitFile(APK_PATH)) {
            messageChange("检测到安装文件 " + APK_PATH);
        } else {
            messageChange("(error)未检测到安装文件 " + APK_PATH);
            return false;
        }

        String apkPackageName = PackageTool.getAppFilePackageName(mContext, APK_PATH);
        if (TextUtils.isEmpty(apkPackageName)) {
            messageChange("(error)检查的apk获取包名失败 ");
            return false;
        } else if (!apkPackageName.equals(WX_PACKAGE_NAME)) {
            messageChange("(error)包名不对 , " + apkPackageName);
            return false;
        } else if (apkPackageName.equals(WX_PACKAGE_NAME)) { //成功，走下一步
            messageChange("应用包名正确可以安装");
        } else {
            messageChange("(error)检查 apk 文件其他错误  ");
            return false;
        }

        //删除data/data/packagename 目录，主要可能是一些特殊原因导致的错误,删除不掉导致不能安装应用
        if (SystemPathTool.exitPath(MM_DATA_ROOT)) {
            messageChange(MM_DATA_ROOT + "源文件缓存目录存在 ");
            boolean removeDirect = SystemPathTool.remove(MM_DATA_ROOT);
            if (removeDirect) {
                messageChange("删除源文件缓存目录成功 " + MM_DATA_ROOT);
            } else {
                messageChange("(error)删除源文件缓存目录失败 " + MM_DATA_ROOT);
                return false;
            }
        } else {
            messageChange(MM_DATA_ROOT + "源文件缓存目录不存在 ");
        }
        //BUG 软连接 在元文件夹删掉之后，链接执行exitPath 返回false,链接不删掉的后果就是apk 安装失败。需要再次执行删除即可解决问题。
        SystemPathTool.remove(MM_DATA_ROOT);

        messageChange("开始安装apk ");
        boolean success = PackageTool.install(APK_PATH);
        if (success) {
            messageChange("安装成功");
        } else {
            messageChange("安装失败");
            return false;
        }

        //检查当前应用的缓存目录是否存在，再次确认应用安装成功
        if (SystemPathTool.exitPath(MM_DATA_ROOT)) {
            messageChange("微信安装成功，应用缓存目录存在" + MM_DATA_ROOT);
        } else {
            messageChange("(error)应用缓存目录不存在 " + MM_DATA_ROOT);
            return false;
        }


        //删除各个帐号的缓存目录数据
        if (SystemPathTool.exitPath(ACCOUNT_DATA_CACHE_PATH)) {
            messageChange("帐号备份数据文件夹存在");
            boolean removeAccountData = SystemPathTool.remove(ACCOUNT_DATA_CACHE_PATH);
            if (removeAccountData) {
                messageChange("删除备份数据文件夹成功" + ACCOUNT_DATA_CACHE_PATH);
            } else {
                messageChange("(error)删除备份数据文件夹失败 " + ACCOUNT_DATA_CACHE_PATH);
                return false;
            }
        } else {
            messageChange("各个帐号的缓存目录数文件夹不存在");
        }

        //创建各个帐号的缓存数据根目录
        boolean mkAccountRootPath = SystemPathTool.mkD(ACCOUNT_DATA_CACHE_PATH);
        if (mkAccountRootPath) {
            messageChange("创建干净数据根目录成功" + ACCOUNT_DATA_CACHE_PATH);
        } else {
            messageChange("(error) 创建干净数据根目录失败" + ACCOUNT_DATA_CACHE_PATH);
            return false;
        }

        //修改帐号缓存目录的权限
        String chmodCmd = "chmod  -R 777 " + ACCOUNT_DATA_CACHE_PATH;
        String chownCmd = "chown system:system " + ACCOUNT_DATA_CACHE_PATH;
        boolean chmodBoolean = SystemPathTool.noResultIsSuccess(chmodCmd);
        boolean chownBoolean = SystemPathTool.noResultIsSuccess(chownCmd);
        if (!chmodBoolean) {
            messageChange("(error) 修改文件权限失败" + ACCOUNT_DATA_CACHE_PATH + chmodCmd);
            return false;
        } else if (!chownBoolean) {
            messageChange("(error) 修改文件所有者失败" + ACCOUNT_DATA_CACHE_PATH + chownCmd);
            return false;
        } else {
            messageChange("修改文件所有者和修改文件权限成功" + ACCOUNT_DATA_CACHE_PATH);
        }

        //创建一个干净的数据目录，供创建帐号的时候复制
        boolean backClean = SystemPathTool.copy(MM_DATA_ROOT, CLEAN_DATA_FOLDER_PATH);
        if (backClean) {
            messageChange("创建干净数据成功" + CLEAN_DATA_FOLDER_PATH);
        } else {
            messageChange("(error) 创建干净数据库失败" + CLEAN_DATA_FOLDER_PATH);
            return false;
        }

        //创建一个测试的数据目录，供测试应用可运行
        boolean backTest = SystemPathTool.copy(MM_DATA_ROOT, TEST_DATA_FOLDER_PATH);
        if (backTest) {
            messageChange("创建测试数据成功" + TEST_DATA_FOLDER_PATH);
        } else {
            messageChange("(error) 创建测试数据失败" + TEST_DATA_FOLDER_PATH);
            return false;
        }

        //删除原应用的缓存目录，然后在创建指向单独的缓存目录链接
        boolean removeDataData = SystemPathTool.remove(MM_DATA_ROOT);
        if (removeDataData) {
            messageChange("删除源data目录成功" + MM_DATA_ROOT);
        } else {
            messageChange("(error) 删除源data目录失败" + MM_DATA_ROOT);
            return false;
        }

        //把应用的缓存目录链接指向测试地址
        boolean linkSuccess = SystemPathTool.Link(TEST_DATA_FOLDER_PATH, MM_DATA_ROOT);
        if (linkSuccess) {
            messageChange("创建测试目录链接成功");
        } else {
            messageChange("(error) 创建测试目录链接失败");
            return false;
        }
        if (PackageTool.launchAppFormPackage(mContext, WX_PACKAGE_NAME)) {
            messageChange("启动应用成功");
        } else {
            messageChange("启动应用失败");
        }
        return true;
    }


    private String getCurrentAccount() {
        String accountFile = MM_DATA_ROOT + "/" + ACCOUNT_NAME_FILE_NAME;
        if (SystemPathTool.exitFile(accountFile)) {
            return SystemPathTool.getOutPutContent(accountFile);
        } else {
            return "";
        }
    }

    private boolean stopWeixin() {
        String command = "am force-stop " + WX_PACKAGE_NAME;
        boolean stopPackageName = SystemPathTool.noResultIsSuccess(command);
        if (stopPackageName) {
            messageChange("强制停止应用成功");
            return true;
        } else {
            messageChange("(error)强制停止应用失败，暂时放过");
            return true;
//            return false;
//            return false;
        }
    }

    public String deleteAccount(String account) {
        String accountPath = AccountManager.ACCOUNT_DATA_CACHE_PATH + account;
        if (SystemPathTool.exitFile(accountPath)) {
            final boolean remored = SystemPathTool.remove(accountPath);
            if (remored) {
                return SUCCESS_TAG;
            } else {
                return "删除帐号 失败 ";
            }
        } else {
            return "帐号目录不存在" + account;
        }
    }

    public String switchContext(String nextAccount) {
        if (TextUtils.isEmpty(nextAccount)) {
            return "切换的帐号为空";
        }

        String newAccountCache = ACCOUNT_DATA_CACHE_PATH + nextAccount;

        String checkContext = checkContextTag();
        if (!SUCCESS_TAG.equals(checkContext)) {
            return "检查环境失败" + checkContext;
        }

        String currentAccount = getCurrentAccount();
        LogManager.getInstance().logInfo("当前帐号是" + currentAccount);
        if (nextAccount.equals(currentAccount)) { //当前帐号属于同一账号,只需要后面检查设备信息即可

        } else {
            //当前帐号不是下次切换的帐号
            if (stopWeixin()) {
                boolean exit = SystemPathTool.exitPath(newAccountCache);
                if (!exit) {
                    messageChange("不存在帐号的缓存目录，就复制一份新的出来");
                    boolean copyNewCache = SystemPathTool.copy(CLEAN_DATA_FOLDER_PATH, newAccountCache);
                    if (!copyNewCache) {
                        return "复制新帐号缓存目录失败";
                    }
                } else {
                    LogManager.getInstance().logInfo("切换的帐号缓存信息存在");
                }
            } else {
                return "强制停止应用失败";
            }
            //删除/data/data/packagename软链接 或者文件
            boolean rmLink = SystemPathTool.remove(MM_DATA_ROOT);
            if (!rmLink) {
                return "删除链接文件失败";
            } else {
                LogManager.getInstance().logInfo("删除 " + MM_DATA_ROOT + "成功");
            }
            //创建文件链接

            boolean linkSuccess = SystemPathTool.Link(newAccountCache, MM_DATA_ROOT);
            if (!linkSuccess) {
                return "创建链接文件失败";
            } else {
                LogManager.getInstance().logInfo("创建链接文件 " + MM_DATA_ROOT + "成功");
            }
        }
        //此处写入帐号信息，正好检测连接文件是否成功
        String accountPath = newAccountCache + "/" + ACCOUNT_NAME_FILE_NAME;
        if (!SystemPathTool.exitFile(accountPath)) {
            String writeAccount = "echo " + nextAccount + " > " + accountPath;
            boolean writeSuccess = SystemPathTool.noResultIsSuccess(writeAccount);
            if (!writeSuccess) {
                return "写入帐号信息失败";
            } else {
                LogManager.getInstance().logInfo("写入帐号信息成功 帐号 =  " + nextAccount);
            }
        } else {
            LogManager.getInstance().logInfo("已经存在帐号信息 " + SystemPathTool.getOutPutContent(accountPath));
        }

        String deviceInfoFile = newAccountCache + "/" + ACCOUNT_DEVICE_INFO_FILE_NAME;

        if (!SystemPathTool.exitFile(deviceInfoFile)) {
            //下面就开始检查设备信息了
            String deviceInfos = DeviceInfoManager.getInstance().getDeviceInfo();
            if (TextUtils.isEmpty(deviceInfos)) {
                return "获取设备信息失败";
            }
            try {
                new JSONObject(deviceInfos);
            } catch (JSONException e) {
                e.printStackTrace();
                return deviceInfos;
            }
            LogManager.getInstance().logInfo("新的设备信息" + deviceInfos);
            String codeInfo = null;
            try {
                codeInfo = URLEncoder.encode(deviceInfos, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return "编码失败";
            }
            if (TextUtils.isEmpty(codeInfo)) {
                LogManager.getInstance().logError("codeInfo URLEncoder is null ");
                return "编码后为空";
            }

            String writeDevice = "echo " + codeInfo + " > " + deviceInfoFile;
            boolean writeSuccess = SystemPathTool.noResultIsSuccess(writeDevice);
            if (!writeSuccess) {
                return "写入信息失败";
            }
        } else {
            LogManager.getInstance().logInfo("已经存在帐号设备信息");
        }

        if (!changeSdPath(currentAccount, nextAccount)) {
            return "切换sd卡目录失败";
        }

        return SUCCESS_TAG;
    }

    public static String writeDeviceInfo() {
        String deviceInfos = DeviceInfoManager.getInstance().getDeviceInfo();
        if (TextUtils.isEmpty(deviceInfos)) {
            return "获取设备信息失败";
        }
        try {
            new JSONObject(deviceInfos);
        } catch (JSONException e) {
            e.printStackTrace();
            return deviceInfos;
        }
        LogManager.getInstance().logInfo("新的设备信息" + deviceInfos);
        String codeInfo = null;
        try {
            codeInfo = URLEncoder.encode(deviceInfos, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "编码失败";
        }
        if (TextUtils.isEmpty(codeInfo)) {
            LogManager.getInstance().logError("codeInfo URLEncoder is null ");
            return "编码后为空";
        }

        String writeDevice = "echo " + codeInfo + " > " + DEVICE_FILE;
        boolean writeSuccess = SystemPathTool.noResultIsSuccess(writeDevice);
        if (!writeSuccess) {
            return "写入信息失败";
        }
        return SUCCESS_TAG;
    }

    public boolean switchContext(String accountPhone, String deviceInfoJson) {

        LogManager.getInstance().logInfo("switchContext accountPhone = " + accountPhone);
        if (TextUtils.isEmpty(accountPhone)) {
            messageChange("切换帐号帐号为空");
            return false;
        }
        if (!checkContext()) {
            messageChange("环境检测失败");
            return false;
        }

        String command = "am force-stop " + WX_PACKAGE_NAME;
        boolean stopPackageName = SystemPathTool.noResultIsSuccess(command);
        if (stopPackageName) {
            messageChange("强制停止应用成功");
        } else {
            messageChange("(error)强制停止应用失败，暂时放过");
//            return false;
        }

        String oldAccount = "";
        String oldPath = MM_DATA_ROOT + "/files/" + ACCOUNT_NAME_FILE_NAME;

        if (SystemPathTool.exitFile(oldPath)) {
            oldAccount = SystemPathTool.getOutPutContent(oldPath);
        }
        if (TextUtils.isEmpty(oldAccount)) {
            messageChange("(war ) oldAccount is null");
        }

        //如果已经是当前环境了就不切换了，start
//        String accountPath = AccountManager.MM_DATA_ROOT + "/files/" + AccountManager.ACCOUNT_NAME_FILE_NAME;
//        String account_name = SystemPathTool.getOutPutContent(accountPath);
//        if (!TextUtils.isEmpty(account_name) && account_name.equals(accountPhone)) {
//            sendSwitchState(true);
//            return true;
//        }
        //如果已经是当前环境了就不切换了，end

        if (SystemPathTool.exitPath(CLEAN_DATA_FOLDER_PATH)) {
            messageChange("存在干净的缓存环境");
        } else {
            messageChange(" 没有干净的的缓存环境目录");
            return false;
        }

        //如果不存在目录 复制干净的数据目录到新帐号目录
        String newAccountCache = ACCOUNT_DATA_CACHE_PATH + accountPhone;

        if (SystemPathTool.exitPath(newAccountCache)) {
            messageChange("已经存在切换帐号缓存目录 " + newAccountCache);
            //缓存目录存在就直接指向即可
        } else {
            messageChange("切换帐号缓存目录不存在 " + newAccountCache);
            //缓存目录不存在，复制一份新的，然后在从新指向
            boolean cpNewData = SystemPathTool.copy(CLEAN_DATA_FOLDER_PATH, newAccountCache);
            if (cpNewData) {
                messageChange("切换帐号，创建新的数据缓存目录成功" + newAccountCache);
            } else {
                messageChange("(error) 创建干净数据库失败" + newAccountCache);
                return false;
            }
        }


        String fileDir = newAccountCache + "/files/";
        if (!SystemPathTool.exitPath(fileDir)) {
            messageChange("创建目录 = " + fileDir);
            if (!SystemPathTool.mkDir(fileDir)) {
                messageChange("error 创建file目录失败" + fileDir);
                return false;
            }
        }
        //把帐号信息写入到file目录下面
        String accountInfoFile = fileDir + ACCOUNT_NAME_FILE_NAME;
        String writePhone = "echo " + accountPhone + " > " + accountInfoFile;
        boolean writeAccount = SystemPathTool.noResultIsSuccess(writePhone);
        if (writeAccount) {
            messageChange("写入帐号信息成功");
        } else {
            messageChange("(error) 写入帐号信息失败");
            return false;
        }

        String chmodCmd = "busybox chmod 777 -R " + accountInfoFile;
        String chownCmd = "chown system:system " + accountInfoFile;

        boolean chmodBoolean = SystemPathTool.noResultIsSuccess(chmodCmd);
        boolean chownBoolean = SystemPathTool.noResultIsSuccess(chownCmd);

        if (!chmodBoolean) {
            messageChange("(error) 修改文件权限失败" + chmodCmd);
            return false;
        } else if (!chownBoolean) {
            messageChange("(error) 修改文件所有者失败" + chownCmd);
            return false;
        } else {
            messageChange("修改文件所有者和修改文件权限成功" + newAccountCache);
        }


        //不管之前是否存在过，都需要执行，删除 /data/data/packagename目录,然后在创建链接
        if (SystemPathTool.exitPath(MM_DATA_ROOT)) {
            messageChange("源文件缓存目录存在 " + MM_DATA_ROOT);

            boolean removeDataData = SystemPathTool.remove(MM_DATA_ROOT);
            if (removeDataData) {
                messageChange("删除源文件缓存目录成功 " + MM_DATA_ROOT);
            } else {
                messageChange("删除源文件缓存目录失败 " + MM_DATA_ROOT);
                return false;
            }
        } else {
            messageChange("源文件缓存目录不存在 " + MM_DATA_ROOT);
        }

        if (!SystemPathTool.exitPath(fileDir)) {
            messageChange("创建目录 = " + fileDir);
            if (!SystemPathTool.mkDir(fileDir)) {
                messageChange("error 创建file目录失败" + fileDir);
                return false;
            }
        }
        if (!KEY_TEST_DEVICE_INFO.equals(deviceInfoJson)) { //测试人员切换帐号，就不用传入设备信息，用之前用过的设备信息即可
            //把设备信息写入到files目录下面
            String deviceInfoFile = fileDir + ACCOUNT_DEVICE_INFO_FILE_NAME;
            String codeInfo = null;
            try {
                codeInfo = URLEncoder.encode(deviceInfoJson, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (TextUtils.isEmpty(codeInfo)) {
                LogManager.getInstance().logError("codeInfo URLEncoder is null ");
                return false;
            }
            String writeDevice = "echo " + codeInfo + " > " + deviceInfoFile;
            boolean writeSuccess = SystemPathTool.noResultIsSuccess(writeDevice);
            if (writeSuccess) {
                messageChange("写入设备信息成功");
            } else {
                messageChange("(error) 写入帐号信息失败");
                return false;
            }
        }

        File mmLogFile = new File("/storage/emulated/0/tbslog/tbslog.txt");
        if (mmLogFile.exists()) {
            boolean delete = mmLogFile.delete();
            if (delete) {
                messageChange("删除日志文件 " + mmLogFile.getAbsolutePath() + " 成功");
            } else {
                messageChange("(error)删除日志文件 " + mmLogFile.getAbsolutePath() + " 失败");
            }
        }

        //删除然链接之后，创建链接
        boolean linkSuccess = SystemPathTool.Link(newAccountCache, MM_DATA_ROOT);
        if (KEY_TEST_DEVICE_INFO.equals(deviceInfoJson)) {
            if (linkSuccess) {
                messageChange("创建新缓存目录链接成功" + newAccountCache);
                //-------switch sd path start------
                if (!changeSdPath(oldAccount, accountPhone)) {
                    messageChange("改变目录失败");
                    return false;
                }
                //-------switch sd path end------
                return true;
            } else {
                messageChange("(error) 创建测试目录链接失败" + newAccountCache);
                return false;
            }
        }

        //-------switch sd path start------
        if (!changeSdPath(oldAccount, accountPhone)) {
            messageChange("切换sd卡目录失败");
            return false;
        }
        //-------switch sd path end------

        if (linkSuccess) {
            messageChange("创建新缓存目录链接成功" + newAccountCache);
            return true;
        } else {
            messageChange("(error) 创建测试目录链接失败" + newAccountCache);
            return false;
        }
    }

    //试用mv命名来改变文件位置 ,名称约定，1，app缓存文件，即使微信在sd卡上的缓存文件，2，旧缓存，2，缓存
    //执行过程需要两个步骤，1，把现在的缓存目录保存起来，2，把之前的缓存目录拿过来
    //检查工作，1，app文件缓存是否存在,旧缓存是否存在  2，之前文件是否存在，app文件缓存是否存在
    private boolean changeSdPath(String oldAccount, String account) {
        messageChange(" 开始改变sd卡目录文件 oldAccount = " + oldAccount + " account = " + account);

        if (TextUtils.isEmpty(oldAccount)) {
            messageChange("oldAccount =  is null");
            return true;
        }
        if (oldAccount.equals(account)) {
            messageChange("帐号相同不需要切换");
            return true;
        }

        //first step start
        File weixinSdCache = new File(MM_SD_PATH);
        if (!weixinSdCache.exists()) {
            boolean createMM = weixinSdCache.mkdirs();
            if (!createMM) {
                messageChange("(error) 创建MM文件失败 " + MM_SD_PATH);
            }
        }
        File oldCache = new File(MM_SD_CACHE_PATH, oldAccount);
        if (oldCache.exists()) {
            messageChange("(warring) 旧缓存存在 " + oldCache); //mv命名是移动命令，都成功的话，是不应该存在旧缓存目录的
            boolean removeOldCache = SystemPathTool.remove(oldCache.getAbsolutePath());
            if (!removeOldCache) {
                messageChange("(error) 删除旧缓存失败 " + oldCache);
                return false;
            }
        }
        String saveOldCacheCommand = "mv  " + MM_SD_PATH + " " + oldCache.getAbsolutePath();

        Shell.ShellCommand command = Shell.runAsRoot(saveOldCacheCommand);
        if (command.output != null && command.output.size() <= 0) {
            messageChange("移动缓存目录成功 " + saveOldCacheCommand);
        } else {
            messageChange("(error)移动缓存目录失败 " + saveOldCacheCommand);
            messageChange("(error) " + command.output);
            return false;
        }
        //first step end

        //-------------------------------------------------------
        //second step star
        File newCacheFile = new File(MM_SD_CACHE_PATH, account);
        if (!newCacheFile.exists()) {
            boolean createNewFile = newCacheFile.mkdirs();
            if (!createNewFile) {
                messageChange("(error)  创建新的缓存目录失败" + newCacheFile.getAbsolutePath());
            }
        }


        weixinSdCache = new File(MM_SD_PATH);
        if (weixinSdCache.exists()) {
            messageChange("(waring) " + MM_SD_PATH + "  存在 ");
            boolean removeDirect = SystemPathTool.remove(MM_SD_PATH);
            if (!removeDirect) {
                messageChange("(error) 删除文件失败 " + MM_SD_PATH);
                return false;
            }
        }

        String useNewCacheCommand = "mv  " + newCacheFile.getAbsolutePath() + " " + MM_SD_PATH;

        command = Shell.runAsRoot(useNewCacheCommand);
        if (command.output != null && command.output.size() <= 0) {
            messageChange("移动新帐号缓存成功 " + useNewCacheCommand);
        } else {
            messageChange("(error)移动新帐号缓存失败 " + saveOldCacheCommand);
            messageChange("(error) " + command.output);
            return false;
        }
        //second step end


//        File cacheRoot = new File(MM_CACHE_ROOT);
//        if (!cacheRoot.exists()) {
//            boolean success = cacheRoot.mkdirs();
//            if (success) {
//                messageChange("创建目录 " + cacheRoot.getAbsolutePath() + " 成功");
//            } else {
//                messageChange("(error)创建目录 " + cacheRoot.getAbsolutePath() + " 失败");
//                return false;
//            }
//        }
//
//
//        File oldCache = new File(MM_CACHE_ROOT, oldAccount);
//
//
//        if (oldCache.exists()) {
//            boolean removeOldCache = SystemPathTool.removeDirect(oldCache.getAbsolutePath());
//            if (removeOldCache) {
//                messageChange("删除旧缓存目录成功");
//            } else {
//                messageChange("(error)删除旧缓存目录失败");
//                return false;
//            }
//        }
//
//        File SdCacheFile = new File(MM_SD_PATH);
//        if (!SdCacheFile.exists()) {
//            boolean createCache = SdCacheFile.mkdirs();
//            LogManager.getInstance().logError("(error)" + MM_SD_PATH + "不存在，创建失败");
//            if (!createCache) {
//                return false;
//            }
//        }
//
//        boolean saveOldCache = SystemPathTool.copyDirect(MM_SD_PATH, oldCache.getAbsolutePath());
//        if (saveOldCache) {
//            messageChange("存储就缓存成功");
//        } else {
//            messageChange("(error)存储旧缓存失败");
//            return false;
//        }
//
//        File mmRootCache = new File(MM_SD_PATH);
//        if (mmRootCache.exists()) {
//            boolean removeMmCacheRoot = SystemPathTool.removeDirect(mmRootCache.getAbsolutePath());
//            if (removeMmCacheRoot) {
//                messageChange("删除缓存根目录成功 " + mmRootCache.getAbsolutePath());
//            } else {
//                messageChange("(error)删除缓存根目录失败 " + mmRootCache.getAbsolutePath());
//                return false;
//            }
//        }
//
//
//        File newCacheFile = new File(cacheRoot, account);
//        if (newCacheFile.exists()) {
//            boolean cpNewCache = SystemPathTool.copyDirect(newCacheFile.getAbsolutePath(), MM_SD_PATH);
//            if (cpNewCache) {
//                messageChange("旧缓存存在,复制 MM 系统根目录 成功");
//            } else {
//                messageChange("(error)旧缓存存在,复制 MM 系统根目录 失败");
//                return false;
//            }
//        } else {
//            boolean success = mmRootCache.mkdirs();
//            if (success) {
//                messageChange("创建目录 " + mmRootCache.getAbsolutePath() + " 成功");
//            } else {
//                messageChange("(error)创建目录 " + mmRootCache.getAbsolutePath() + " 失败");
//                return false;
//            }
//        }
//        if (SystemPathTool.exitPath(MM_SD_PATH)) {
//            messageChange("源文件缓存目录存在 " + MM_SD_PATH);
//
//            boolean removeDataData = SystemPathTool.removeDirect(MM_SD_PATH);
//            if (removeDataData) {
//                messageChange("删除源文件SD目录成功 " + MM_SD_PATH);
//            } else {
//                messageChange("删除源文件SD目录失败 " + MM_SD_PATH);
//                return false;
//            }
//        } else {
//            messageChange("目录不存在 " + MM_SD_PATH);
//        }

//        String newSdPath = phoneFile.getAbsolutePath();


        //删除然链接之后，创建链接
//        boolean linkSuccess = SystemPathTool.LinkDirect(newSdPath, MM_SD_PATH);
//        if (linkSuccess) {
//            messageChange("创建 SD 卡链接 成功" + newSdPath);
//        } else {
//            messageChange("(error) 创建测试目录链接失败" + newSdPath);
//            return false;
//        }

        return true;
    }

//    StringBuffer sb = new StringBuffer();

    private void messageChange(String msg) {
        LogManager.getInstance().logInfo(msg);
//        if (sb.length() > 1024) {
//            sb = new StringBuffer();
//        }
//        sb.append(msg).append("\n");
//        Intent i = new Intent(ACTION_MESSAGE_CHANGE);
//        android.os.Bundle bundle = new Bundle();
//        bundle.putString(KEY_MSG, sb.toString());
//        i.putExtras(bundle);
//        mContext.sendBroadcast(i);
    }

    public static boolean isAccountFile(String fileName) {
        if (!"clean".equals(fileName) && !"test".equals(fileName) && !"net.txt".equals(fileName) && !"localdev.txt".equals(fileName)) {
            return true;
        }
        return false;
    }

    public static boolean writeLocation(String location) {
        if (SystemPathTool.exitFile(AccountManager.LOCATION_FILE)) {
            SystemPathTool.remove(AccountManager.LOCATION_FILE);
        }

        String LocationInfo;
        try {
            LocationInfo = URLEncoder.encode(location, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            LogManager.getInstance().logError("编码失败");
            return false;
        }
        if (TextUtils.isEmpty(LocationInfo)) {
            LogManager.getInstance().logError("writeLocation 编码后为空");
            return false;
        }

        String writeAccount = "echo " + LocationInfo + " > " + AccountManager.LOCATION_FILE;
        return SystemPathTool.noResultIsSuccess(writeAccount);
    }

    public static boolean haveLocation() {
        return SystemPathTool.exitFile(AccountManager.LOCATION_FILE);
    }

    public static boolean removeLocation() {
        return SystemPathTool.remove(AccountManager.LOCATION_FILE);
    }
}
